#include "orderLoad.h"
#include <string.h>
#include <stdlib.h>
int loadOrders(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int ordercount=getFileInfo(ptr_file,&maxlinelen);
	orderdata=(struct OrderVars*) calloc(ordercount,sizeof(struct OrderVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<ordercount;i++){
		fgets(buf,maxlinelen,ptr_file);
		strcpy(orderdata[i].id,strtok(buf,"/"));
		strcpy(orderdata[i].date,strtok(NULL,"/"));
		strcpy(orderdata[i].clientid,strtok(NULL,"/"));
		strcpy(orderdata[i].deliverytype,strtok(NULL,"/"));
		strcpy(orderdata[i].locker,strtok(NULL,"/"));
		strcpy(orderdata[i].giftcard,strtok(NULL,"/"));
		strcpy(orderdata[i].coupon,strtok(NULL,"/"));
	}
	fclose(ptr_file);
	return 0;
}

int writeOrders(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<ordercount;i++){
		fprintf(ptr_file,"%s/%s/%s/%s/%s/%s/%s\n",orderdata[i].id,orderdata[i].date,orderdata[i].clientid,orderdata[i].deliverytype,orderdata[i].locker,orderdata[i].giftcard,orderdata[i].coupon);
	}
	fclose(ptr_file);
	free(orderdata);
	return 0;
}

void addOrder(struct OrderVars n){
	orderdata=(struct OrderVars*) realloc(orderdata,++ordercount*sizeof(struct OrderVars));
	orderdata[ordercount-1]=n;
}

void rmOrder(int index){
	for(int i=index;i<ordercount-1;i++){
		orderdata[i]=orderdata[i+1];
	}
	orderdata=(struct OrderVars*) realloc(orderdata,--ordercount*sizeof(struct OrderVars));
}
